Public Class frmMain
    Dim objRandom As New Random
    Dim WithEvents inet As New Net.WebClient
    Dim watchVolume As Boolean = True
    Dim lastMovement As Date
    Dim files() As String

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim media As WMPLib.IWMPMedia
        Dim i As Integer

        files = IO.Directory.GetFiles("c:\pictures", "*.jpg", IO.SearchOption.AllDirectories)

        lastMovement = Now
        If IO.Directory.Exists("f:\music") Then
            txtMusicFolder.Text = "f:\music" 'Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)
        Else
            txtMusicFolder.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic)
        End If

        Me.Bounds = Screen.PrimaryScreen.Bounds
        refreshSongs()

        If gridSongs.Rows.Count > 0 Then
            RemoveHandler player.CurrentItemChange, AddressOf player_CurrentItemChange

            i = objRandom.Next(0, gridSongs.Rows.Count)
            player.currentPlaylist.clear()
            media = player.newMedia(gridSongs.Rows(i).Tag)
            media.setItemInfo("row", gridSongs.Rows(i).Index)
            player.currentPlaylist.appendItem(media)
            gridSongs.Rows(i).Selected = True
            gridSongs.FirstDisplayedScrollingRowIndex = i
            showAlbumArt(gridSongs.Rows(i).Cells(2).Value, gridSongs.Rows(i).Cells(1).Value)
            i = objRandom.Next(0, gridSongs.Rows.Count)
            media = player.newMedia(gridSongs.Rows(i).Tag)
            media.setItemInfo("row", gridSongs.Rows(i).Index)
            player.currentPlaylist.appendItem(media)

            player.Ctlcontrols.play()

            AddHandler player.CurrentItemChange, AddressOf player_CurrentItemChange
        End If
        volume.Value = player.settings.volume
    End Sub

    Private Sub BtnRefreshSongs_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefreshSongs.Click
        refreshSongs()
    End Sub

    Public Sub refreshSongs()
        Dim files As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
        Dim currFile As String
        Dim i As Integer
        Dim mp3 As modSongInfo.ID3V1Tag
        Dim wma As modSongInfo.WMAID3Tag
        Dim myTitle As String
        Dim myArtist As String
        Dim myAlbum As String

        gridSongs.Rows.Clear()

        files = FileIO.FileSystem.GetFiles(txtMusicFolder.text, FileIO.SearchOption.SearchAllSubDirectories, "*.mp3", "*.wma")
        For Each currFile In files
            i = gridSongs.Rows.Add()
            gridSongs.Rows(i).Tag = currFile
            myTitle = ""
            myArtist = ""
            myAlbum = ""
            If IO.Path.GetExtension(currFile).ToLower = ".mp3" Then
                mp3 = New modSongInfo.ID3V1Tag(currFile)
                myTitle = mp3.title
                myArtist = mp3.artist
                myAlbum = mp3.album
                mp3 = Nothing
            ElseIf IO.Path.GetExtension(currFile).ToLower = ".wma" Then
                wma = New modSongInfo.WMAID3Tag(currFile)
                myTitle = wma.title
                myArtist = wma.artist
                myAlbum = wma.album
                wma = Nothing
            End If
            If myTitle <> Nothing Then myTitle = myTitle.Replace(ControlChars.NullChar, "")
            If myArtist <> Nothing Then myArtist = myArtist.Replace(ControlChars.NullChar, "")
            If myAlbum <> Nothing Then myAlbum = myAlbum.Replace(ControlChars.NullChar, "")
            If myTitle = "" Or myTitle = Nothing Then
                myTitle = IO.Path.GetFileNameWithoutExtension(currFile)
            End If
            gridSongs.Rows(i).Cells(0).Value = myTitle
            gridSongs.Rows(i).Cells(1).Value = myArtist
            gridSongs.Rows(i).Cells(2).Value = myAlbum
        Next
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Application.Exit()
    End Sub

    Private Sub gridSongs_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles gridSongs.DoubleClick
        Dim media As WMPLib.IWMPMedia
        Dim i As Integer

        RemoveHandler player.CurrentItemChange, AddressOf player_CurrentItemChange

        i = objRandom.Next(0, gridSongs.Rows.Count)
        player.currentPlaylist.clear()
        media = player.newMedia(gridSongs.SelectedRows(0).Tag)
        media.setItemInfo("row", gridSongs.SelectedRows(0).Index)
        player.currentPlaylist.appendItem(media)
        showAlbumArt(gridSongs.SelectedRows(0).Cells(1).Value, gridSongs.SelectedRows(0).Cells(2).Value)
        media = player.newMedia(gridSongs.Rows(i).Tag)
        media.setItemInfo("row", gridSongs.Rows(i).Index)
        player.currentPlaylist.appendItem(media)

        player.Ctlcontrols.play()

        AddHandler player.CurrentItemChange, AddressOf player_CurrentItemChange
    End Sub

    Private Sub player_CurrentItemChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_CurrentItemChangeEvent) Handles player.CurrentItemChange
        Dim media As WMPLib.IWMPMedia
        Dim i As Integer

        i = objRandom.Next(0, gridSongs.Rows.Count)
        media = player.newMedia(gridSongs.Rows(i).Tag)
        media.setItemInfo("row", i)
        player.currentPlaylist.appendItem(media)
        gridSongs.Rows(player.currentMedia.getItemInfo("row")).Selected = True
        gridSongs.FirstDisplayedScrollingRowIndex = player.currentMedia.getItemInfo("row")
        player.Ctlcontrols.play()

        If player.currentPlaylist.count > 100 Then
            player.currentPlaylist.removeItem(player.currentPlaylist.Item(0))
        End If

        showAlbumArt(gridSongs.Rows(player.currentMedia.getItemInfo("row")).Cells(1).Value, gridSongs.Rows(player.currentMedia.getItemInfo("row")).Cells(2).Value)
    End Sub

    Private Sub player_DurationUnitChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_DurationUnitChangeEvent) Handles player.DurationUnitChange
        lblSongDuration.Text = player.currentMedia.markerCount
        lblSSTime.Text = player.currentMedia.markerCount
    End Sub

    Public Sub newSong(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_MediaChangeEvent) Handles player.MediaChange
        'showAlbumArt(gridSongs.SelectedRows(0).Cells(2).Value, gridSongs.SelectedRows(0).Cells(1).Value)
        Try
            If Not player.Ctlcontrols.currentItem Is Nothing Then
                lblSong.Text = player.Ctlcontrols.currentItem.getItemInfo("title")
                lblArtist.Text = player.Ctlcontrols.currentItem.getItemInfo("artist")
                lblAlbum.Text = player.Ctlcontrols.currentItem.getItemInfo("album")
                lblSSArtist.Text = lblSong.Text & " - " & lblArtist.Text
            End If
        Catch
        End Try
    End Sub

    Private Sub player_PlayStateChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_PlayStateChangeEvent) Handles player.PlayStateChange
        Dim i As Integer

        If e.newState = 8 Then
            Dim media As WMPLib.IWMPMedia
            i = objRandom.Next(0, gridSongs.Rows.Count)
            media = player.newMedia(gridSongs.Rows(i).Tag)
            media.setItemInfo("row", i)
            player.currentPlaylist.appendItem(media)
            gridSongs.Rows(i).Selected = True

            If player.currentPlaylist.count > 100 Then
                player.currentPlaylist.removeItem(player.currentPlaylist.Item(0))
            End If
        End If
    End Sub

    Private Sub TabControl2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TabControl2.SelectedIndexChanged
        Dim artist As String
        Dim song As String

        If TabControl2.SelectedIndex = 1 Then
            artist = gridSongs.Rows(player.currentMedia.getItemInfo("row")).Cells(1).Value
            artist = artist.Replace(" ", "+")
            song = gridSongs.Rows(player.currentMedia.getItemInfo("row")).Cells(0).Value
            song = song.Replace(" ", "+")
            webLyrics.Navigate("http://www.google.com/search?btnI=I%27m+Feeling+Lucky&q=" & artist & "+" & song & "+site:lyricsondemand.com")
        End If
    End Sub

    Private Sub webLyrics_DocumentCompleted(ByVal sender As Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles webLyrics.DocumentCompleted
        webLyrics.Document.Window.ScrollTo(275, 500)
    End Sub

    Private Sub player_PositionChange(ByVal sender As Object, ByVal e As AxWMPLib._WMPOCXEvents_PositionChangeEvent) Handles player.PositionChange
        lblSongDuration.Text = player.Ctlcontrols.currentPositionString
        lblSSTime.Text = player.Ctlcontrols.currentPositionString
    End Sub

    Private Sub tmrPosition_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrPosition.Tick
        If player.playState = WMPLib.WMPPlayState.wmppsPlaying Then
            lblSongDuration.Text = player.Ctlcontrols.currentPositionString & "/" & player.currentMedia.durationString
            lblSSTime.Text = player.Ctlcontrols.currentPositionString & "/" & player.currentMedia.durationString
        End If
    End Sub

    Private Sub showAlbumArt(ByVal album As String, Optional ByVal artist As String = "")        
        Dim url As String

        url = "http://www.noworriescomputerhelp.com/loading/loading.gif"
        picAlbumArt.Image = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(url)))
        picAlbumArt.SizeMode = PictureBoxSizeMode.StretchImage

        If album <> Nothing Then album = album.Replace(" ", "+") Else album = ""
        If artist <> Nothing Then artist = artist.Replace(" ", "+") Else artist = ""
        If Not inet.IsBusy Then
            inet.DownloadStringAsync(New Uri("http://www.amazon.com/s/ref=nb_ss_m/103-0183552-1972678?url=search-alias%3Dpopular&field-keywords=" & artist & "+" & album & "&x=0&y=0"), "search")
        End If
    End Sub

    Private Sub handleDownload(ByVal sender As Object, ByVal e As Net.DownloadStringCompletedEventArgs) Handles inet.DownloadStringCompleted
        Dim url As String
        Dim parts() As String
        Dim key As String

        If e.UserState = "search" Then
            parts = Split(e.Result, "<div id=" & ControlChars.Quote & "Results")
            If parts.Length >= 2 Then
                key = parts(1)
                parts = Split(key, "<a href=" & ControlChars.Quote)
                key = parts(1)
                parts = Split(key, ControlChars.Quote)
                key = parts(0)
                If Not inet.IsBusy Then
                    inet.DownloadStringAsync(New Uri(key), "art")
                End If                
            Else
                url = "http://www.noworriescomputerhelp.com/loading/sad.gif"
                picAlbumArt.Image = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(url)))
                picAlbumArt.SizeMode = PictureBoxSizeMode.StretchImage
            End If
        Else
            parts = Split(e.Result, "registerImage")
            If parts.Length >= 3 Then
                key = parts(2)
                parts = Split(key, ControlChars.Quote)
                url = parts(3)
                picAlbumArt.Image = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(url)))
                picAlbumArt.SizeMode = PictureBoxSizeMode.StretchImage
            Else
                url = "http://www.noworriescomputerhelp.com/loading/sad.gif"
                picAlbumArt.Image = New System.Drawing.Bitmap(New IO.MemoryStream(New System.Net.WebClient().DownloadData(url)))
                picAlbumArt.SizeMode = PictureBoxSizeMode.StretchImage
            End If
        End If
    End Sub

    Private Sub volume_Scroll(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles volume.Scroll
        player.settings.volume = volume.Value
    End Sub

    Private Sub tmrVolume_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrVolume.Tick
        If Date.Now.Hour = 21 Then
            If watchVolume Then
                watchVolume = False
                volume.Value = 10
                player.settings.volume = 10
            End If
        Else
            watchVolume = True
        End If
    End Sub

    Private Sub webLyrics_NewWindow(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles webLyrics.NewWindow
        e.Cancel = True
    End Sub

    Sub wakeUpPlayer()
        lastMovement = Now
        picScreenSaver.Visible = False
        'grpPlayer.Visible = True
        lblSSTime.Visible = False
        lblSSArtist.Visible = False
        'picScreenSaver.SendToBack()
        'grpPlayer.BringToFront()
        Me.Cursor = Cursors.Arrow
        Windows.Forms.Cursor.Show()
        Me.Cursor = Cursors.Arrow
    End Sub

    Private Sub tmrScreenSaver_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrScreenSaver.Tick
        Dim i As Integer

        If (Now - lastMovement).Minutes >= 1 And chkScreenSaver.Checked Then
            lblSSTime.Visible = True
            lblSSArtist.Visible = True
            'grpPlayer.SendToBack()
            'grpPlayer.Visible = False
            'picScreenSaver.BringToFront()            
            i = objRandom.Next(0, files.Length - 1)
            picScreenSaver.Image = Drawing.Image.FromFile(files(i))
            Windows.Forms.Cursor.Hide()
            picScreenSaver.Visible = True
        End If
    End Sub

    Private Sub picScreenSaver_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picScreenSaver.MouseDown
        wakeUpPlayer()
    End Sub

    Private Sub picScreenSaver_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picScreenSaver.MouseMove
        If Not e.Delta = 0 And Not e.Button = Windows.Forms.MouseButtons.None Then
            wakeUpPlayer()
        End If
    End Sub

    Private Sub picScreenSaver_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles picScreenSaver.MouseWheel
        wakeUpPlayer()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If dlgMusicFolder.ShowDialog = Windows.Forms.DialogResult.OK Then
            txtMusicFolder.Text = dlgMusicFolder.SelectedPath
        End If
    End Sub
End Class